﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using Menafrinet.ViewModel;
using Epi;
using Epi.Data;
using Epi.Fields;

namespace Menafrinet.View.Controls
{
    /// <summary>
    /// Interaction logic for DataEntryPanel.xaml
    /// </summary>
    public partial class DataEntryPanel : UserControl
    {
        public DataEntryPanel()
        {
            InitializeComponent();
        }

        public DataHelper DataHelper 
        {
            get
            {
                return this.DataContext as DataHelper;
            }
        }

        private void btnPrintRecords_Click(object sender, RoutedEventArgs e)
        {
            string baseFileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString("N");

            StringBuilder htmlBuilder = new StringBuilder();
            htmlBuilder.Append(Menafrinet.Core.Common.GetHtmlHeader().ToString());

            htmlBuilder.AppendLine("<table width=\"100%\" style=\"border: 0px; padding: 0px; margin: 0px; clear: left; width:100%; \">");
            htmlBuilder.AppendLine(" <tr style=\"border: 0px;\">");
            htmlBuilder.AppendLine("  <td width=\"50%\" style=\"border: 0px;\">");
            htmlBuilder.AppendLine("   <p style=\"font-size: 13pt; font-weight: bold; clear: left; text-decoration: underline;\">Menafrinet</p>");
            htmlBuilder.AppendLine("   <p style=\"font-size: 13pt; font-weight: bold; text-decoration: underline;\">Case Line List</p>");
            htmlBuilder.AppendLine("   <p style=\"font-size: 13pt; font-weight: bold;\">Date printed: " + DateTime.Now.ToShortDateString() + "</p>");

            if (!String.IsNullOrEmpty(txtSearch.Text.Trim()))
            {
                htmlBuilder.AppendLine("   <p style=\"font-size: 13pt; font-weight: bold;\">Filter: " + txtSearch.Text.Trim() + "</p>");
            }

            htmlBuilder.AppendLine("  </td>");
            htmlBuilder.AppendLine(" </tr>");
            htmlBuilder.AppendLine("</table>");


            htmlBuilder.AppendLine("<p style=\"font-weight: bold; clear: left;\">&nbsp;</p>");

            htmlBuilder.AppendLine("<table style=\"width: 1200px; border: 4px solid black;\" align=\"left\">");
            htmlBuilder.AppendLine("<thead>");
            htmlBuilder.AppendLine("<tr style=\"border-top: 0px solid black;\">");
            htmlBuilder.AppendLine("<th style=\"width: 180px;\">EPID</th>");
            htmlBuilder.AppendLine("<th style=\"width: 140px;\">Last Name</th>");
            htmlBuilder.AppendLine("<th style=\"width: 140px;\">First Name</th>");
            htmlBuilder.AppendLine("<th style=\"width: 30px;\">Sex</th>");
            htmlBuilder.AppendLine("<th style=\"width: 30px;\">Age</th>");
            htmlBuilder.AppendLine("<th style=\"width: 100px;\">Health Facility</th>");
            htmlBuilder.AppendLine("<th style=\"width: 140px;\">District</th>");
            htmlBuilder.AppendLine("<th style=\"width: 30px;\">Year</th>");
            htmlBuilder.AppendLine("<th style=\"width: 30px;\">Epi<br/>Week</th>");
            htmlBuilder.AppendLine("<th style=\"width: 100px;\">Classification</th>");
            htmlBuilder.AppendLine("<th style=\"width: 100px;\">Outcome</th>");
            htmlBuilder.AppendLine("</tr>");
            htmlBuilder.AppendLine("</thead>");

            htmlBuilder.AppendLine("<tbody>");

            foreach (CaseViewModel caseVM in DataHelper.FilteredCaseCollection)
            {
                htmlBuilder.AppendLine("<tr>");
                htmlBuilder.AppendLine("<td>" + caseVM.EPID + "</td>");
                htmlBuilder.AppendLine("<td>" + caseVM.LastName + "</td>");
                htmlBuilder.AppendLine("<td>" + caseVM.FirstName + "</td>");
                htmlBuilder.AppendLine("<td>" + caseVM.Sex + "</td>");
                
                if (caseVM.AgeYears.HasValue)
                {
                    htmlBuilder.AppendLine("<td align=\"right\">" + caseVM.AgeYears.ToString() + "</td>");
                }
                else
                {
                    htmlBuilder.AppendLine("<td>&nbsp;</td>");
                }
                htmlBuilder.AppendLine("<td>" + caseVM.HealthFacility + "</td>");
                htmlBuilder.AppendLine("<td>" + caseVM.DistrictReporting + "</td>");
                if (caseVM.Year.HasValue)
                {
                    htmlBuilder.AppendLine("<td align=\"right\">" + caseVM.Year.ToString() + "</td>");
                }
                else
                {
                    htmlBuilder.AppendLine("<td>&nbsp;</td>");
                }
                if (caseVM.EpiWeek.HasValue)
                {
                    htmlBuilder.AppendLine("<td align=\"right\">" + caseVM.EpiWeek.ToString() + "</td>");
                }
                else
                {
                    htmlBuilder.AppendLine("<td>&nbsp;</td>");
                }
                htmlBuilder.AppendLine("<td>" + caseVM.Classification + "</td>");
                htmlBuilder.AppendLine("<td>" + caseVM.Outcome + "</td>");

                //if (caseVM.DateRecordCreated.HasValue)
                //{
                //    htmlBuilder.AppendLine("<td align=\"right\">" + caseVM.DateRecordCreated.Value.ToShortDateString() + "</td>");
                //}
                //else
                //{
                //    htmlBuilder.AppendLine("<td>&nbsp;</td>");
                //}

                //if (caseVM.DateRecordUpdated.HasValue)
                //{
                //    htmlBuilder.AppendLine("<td align=\"right\">" + caseVM.DateRecordUpdated.Value.ToShortDateString() + "</td>");
                //}
                //else
                //{
                //    htmlBuilder.AppendLine("<td>&nbsp;</td>");
                //}

                htmlBuilder.AppendLine("</tr>");
            }

            htmlBuilder.AppendLine("</tbody>");
            htmlBuilder.AppendLine("</table>");

            string fileName = baseFileName + ".html";

            System.IO.FileStream fstream = System.IO.File.OpenWrite(fileName);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fstream);
            sw.WriteLine(htmlBuilder.ToString());
            sw.Close();
            sw.Dispose();

            if (!string.IsNullOrEmpty(fileName))
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = "\"" + fileName + "\"";
                proc.StartInfo.UseShellExecute = true;
                proc.Start();
            }
        }

        private void btnNewRecord_Click(object sender, RoutedEventArgs e)
        {
            Epi.Enter.EnterUIConfig uiConfig = Core.Common.GetNewCaseConfig(DataHelper.CaseForm);
            Epi.Windows.Enter.EnterMainForm emf = new Epi.Windows.Enter.EnterMainForm(DataHelper.Project, DataHelper.CaseForm, uiConfig);
            emf.RecordSaved += new SaveRecordEventHandler(emfCases_RecordSaved);
            emf.ShowDialog();
            emf.RecordSaved -= new SaveRecordEventHandler(emfCases_RecordSaved);
        }

        public void emfCases_RecordSaved(object sender, SaveRecordEventArgs e)
        {
            //RefreshCases();
            string caseGuid = e.RecordGuid;
            if (e.Form == DataHelper.CaseForm)
            {
                ((this.DataContext) as DataHelper).UpdateOrAddCase.Execute(caseGuid);
            }
        }

        private void dgRecords_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (dgRecords.SelectedItems.Count == 1)
            {
                IInputElement element = e.MouseDevice.DirectlyOver;
                if (element != null && element is FrameworkElement)
                {
                    if (((FrameworkElement)element).Parent is DataGridCell)
                    {
                        EditCase();
                    }
                }
            }
        }

        private void EditCase()
        {
            Epi.Enter.EnterUIConfig uiConfig = Core.Common.GetExistingCaseConfig(DataHelper.CaseForm);
            Epi.Windows.Enter.EnterMainForm emf = new Epi.Windows.Enter.EnterMainForm(DataHelper.Project, DataHelper.CaseForm, uiConfig);

            int uniqueKey = ((CaseViewModel)dgRecords.SelectedItem).Case.UniqueKey;

            emf.LoadRecord(uniqueKey);
            emf.RecordSaved += new SaveRecordEventHandler(emfCases_RecordSaved);
            emf.ShowDialog();
            emf.RecordSaved -= new SaveRecordEventHandler(emfCases_RecordSaved);
        }

        internal void ResetHeight()
        {
            dgRecords.Visibility = System.Windows.Visibility.Collapsed;

            grdMain.UpdateLayout();

            double maxHeight = grdMain.ActualHeight;
            maxHeight = maxHeight - 380;

            if (maxHeight <= 0) maxHeight = 0;

            dgRecords.MaxHeight = maxHeight;
            dgRecords.Height = maxHeight;
            dgRecords.Visibility = System.Windows.Visibility.Visible;
        }

        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ResetHeight();
        }
    }
}
